<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>群聊 & 私聊</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .container {
            width: 95%;
            max-width: 1200px;
            height: 90vh;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
            display: flex;
        }

        /* 登录界面 */
        .login-section {
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 40px;
        }

        .login-title {
            font-size: 32px;
            color: #6c5ce7;
            margin-bottom: 40px;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .login-form {
            width: 100%;
            max-width: 400px;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .form-label {
            font-size: 14px;
            color: #666;
            font-weight: 500;
        }

        .form-input {
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .form-input:focus {
            outline: none;
            border-color: #6c5ce7;
        }

        .btn {
            padding: 15px 30px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 500;
        }

        .btn-primary {
            background: #6c5ce7;
            color: white;
        }

        .btn-primary:hover {
            background: #5a4fcf;
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #74b9ff;
            color: white;
        }

        .btn-secondary:hover {
            background: #0984e3;
            transform: translateY(-2px);
        }

        /* 聊天界面 */
        .chat-section {
            width: 100%;
            display: none;
            flex-direction: row;
        }

        .chat-section.active {
            display: flex;
        }

        /* 侧边栏 */
        .sidebar {
            width: 300px;
            background: #f8f9fa;
            border-right: 1px solid #e0e0e0;
            display: flex;
            flex-direction: column;
        }

        .user-info {
            padding: 20px;
            background: #6c5ce7;
            color: white;
            text-align: center;
        }

        .user-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: rgba(255,255,255,0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin: 0 auto 10px;
        }

        .chat-tabs {
            display: flex;
            background: #e9ecef;
        }

        .tab-btn {
            flex: 1;
            padding: 15px;
            border: none;
            background: transparent;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .tab-btn.active {
            background: white;
            color: #6c5ce7;
            font-weight: 500;
        }

        .tab-content {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
        }

        /* 群聊操作区 */
        .group-actions {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .group-actions input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        .group-actions button {
            padding: 10px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s;
        }

        .btn-create {
            background: #00b894;
            color: white;
        }

        .btn-join {
            background: #0984e3;
            color: white;
        }

        /* 聊天项目 */
        .chat-item {
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
            border: 2px solid transparent;
        }

        .chat-item:hover {
            background: #e9ecef;
        }

        .chat-item.active {
            background: #6c5ce7;
            color: white;
            border-color: #5a4fcf;
        }

        .chat-item-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 5px;
        }

        .chat-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #74b9ff;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }

        .chat-info h4 {
            font-size: 16px;
            margin-bottom: 2px;
        }

        .chat-info .chat-id {
            font-size: 12px;
            opacity: 0.7;
        }

        /* 主聊天区 */
        .main-chat {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .chat-header {
            padding: 20px;
            background: white;
            border-bottom: 1px solid #e0e0e0;
            text-align: center;
        }

        .chat-title {
            font-size: 20px;
            color: #333;
            margin-bottom: 5px;
        }

        .chat-subtitle {
            font-size: 14px;
            color: #666;
        }

        .messages-container {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f8f9fa;
        }

        .message {
            margin-bottom: 15px;
            max-width: 70%;
            word-wrap: break-word;
        }

        .message.sent {
            margin-left: auto;
            text-align: right;
        }

        .message.received {
            margin-right: auto;
        }

        .message.system {
            margin: 10px auto;
            text-align: center;
            max-width: 80%;
        }

        .message-header {
            font-size: 12px;
            color: #666;
            margin-bottom: 5px;
        }

        .message-content {
            padding: 12px 16px;
            border-radius: 18px;
            font-size: 14px;
            line-height: 1.4;
        }

        .message.sent .message-content {
            background: #6c5ce7;
            color: white;
        }

        .message.received .message-content {
            background: white;
            color: #333;
            border: 1px solid #e0e0e0;
        }

        .message.system .message-content {
            background: #ffeaa7;
            color: #2d3436;
            text-align: center;
        }

        .message.error .message-content {
            background: #ff7675;
            color: white;
        }

        /* 输入区 */
        .input-area {
            padding: 20px;
            background: white;
            border-top: 1px solid #e0e0e0;
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .message-input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 25px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.3s;
        }

        .message-input:focus {
            border-color: #6c5ce7;
        }

        .send-btn {
            padding: 12px 24px;
            background: #6c5ce7;
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s;
        }

        .send-btn:hover {
            background: #5a4fcf;
        }

        .send-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        /* 状态指示器 */
        .status {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 10px 20px;
            border-radius: 20px;
            color: white;
            font-size: 14px;
            z-index: 1000;
        }

        .status.connected {
            background: #00b894;
        }

        .status.disconnected {
            background: #e17055;
        }

        .hidden {
            display: none !important;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                width: 100%;
                height: 100vh;
                border-radius: 0;
            }
            
            .sidebar {
                width: 250px;
            }
            
            .chat-item {
                padding: 10px;
            }
        }

        /* 工具类 */
        .hidden {
            display: none !important;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 登录界面 -->
        <div class="login-section" id="loginSection">
            <div class="login-title">
                💬 群聊 & 私聊
            </div>
            <div class="login-form">
                <div class="form-group">
                    <label class="form-label">服务器地址</label>
                    <select class="form-input" id="serverSelect">
                        <option value="ws://localhost:5000/ws">本地服务器 (localhost:5000)</option>
                        <option value="ws://180.184.50.86:8083/ws">线上服务器 (180.184.50.86:8083)</option>
                        <option value="custom">自定义地址</option>
                    </select>
                </div>
                <div class="form-group hidden" id="customServerGroup">
                    <label class="form-label">自定义WebSocket地址</label>
                    <input type="text" class="form-input" id="customServerInput" placeholder="ws://your-custom-server.com/ws">
                </div>
                
                <div class="form-group">
                    <label class="form-label">用户名</label>
                    <input type="text" class="form-input" id="usernameInput" placeholder="请输入用户名">
                </div>
                <button class="btn btn-primary" onclick="register()">注册新账号</button>
                
                <div class="form-group" style="margin-top: 20px;">
                    <label class="form-label">账号ID</label>
                    <input type="text" class="form-input" id="userIdInput" placeholder="请输入账号ID">
                </div>
                <button class="btn btn-secondary" onclick="login()">登录已有账号</button>
            </div>
        </div>

        <!-- 聊天界面 -->
        <div class="chat-section" id="chatSection">
            <!-- 侧边栏 -->
            <div class="sidebar">
                <div class="user-info">
                    <div class="user-avatar" id="userAvatar">U</div>
                    <div>我的账号: <span id="myUserId">-</span></div>
                    <div>用户名: <span id="myUsername">-</span></div>
                </div>
                
                <div class="chat-tabs">
                    <button class="tab-btn active" onclick="switchTab('private')">私聊</button>
                    <button class="tab-btn" onclick="switchTab('group')">群聊</button>
                </div>
                
                <!-- 私聊标签页 -->
                <div class="tab-content" id="privateTab">
                    <div class="group-actions">
                        <input type="text" id="friendIdInput" placeholder="输入好友账号ID">
                        <button class="btn-join" onclick="startPrivateChat()">开始聊天</button>
                    </div>
                    <div id="privateChats"></div>
                </div>
                
                <!-- 群聊标签页 -->
                <div class="tab-content hidden" id="groupTab">
                    <div class="group-actions">
                        <input type="text" id="groupNameInput" placeholder="群聊名称">
                        <button class="btn-create" onclick="createGroup()">创建群聊</button>
                    </div>
                    <div class="group-actions">
                        <input type="text" id="groupIdInput" placeholder="群聊ID">
                        <button class="btn-join" onclick="joinGroup()">加入群聊</button>
                    </div>
                    <div id="groupChats"></div>
                </div>
            </div>
            
            <!-- 主聊天区 -->
            <div class="main-chat">
                <div class="chat-header">
                    <div class="chat-title" id="chatTitle">选择一个聊天开始对话</div>
                    <div class="chat-subtitle" id="chatSubtitle">私聊或群聊</div>
                </div>
                
                <div class="messages-container" id="messagesContainer">
                    <div class="message system">
                        <div class="message-content">欢迎使用聊天系统！选择左侧的聊天开始对话。</div>
                    </div>
                </div>
                
                <div class="input-area">
                    <input type="text" class="message-input" id="messageInput" placeholder="输入消息..." disabled>
                    <button class="send-btn" id="sendBtn" onclick="sendMessage()" disabled>发送</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 状态指示器 -->
    <div class="status disconnected" id="status">未连接</div>

    <script>
        class ChatApp {
            constructor() {
                this.ws = null;
                this.isConnected = false;
                this.currentUser = null;
                this.currentChat = null; // { type: 'private'|'group', id: string, name: string }
                this.privateChatData = new Map(); // friendId -> chat info
                this.groupChatData = new Map(); // groupId -> group info
                
                this.initElements();
                this.connect();
            }

            initElements() {
                this.loginSection = document.getElementById('loginSection');
                this.chatSection = document.getElementById('chatSection');
                this.usernameInput = document.getElementById('usernameInput');
                this.userIdInput = document.getElementById('userIdInput');
                this.serverSelect = document.getElementById('serverSelect');
                this.customServerGroup = document.getElementById('customServerGroup');
                this.customServerInput = document.getElementById('customServerInput');
                this.myUserId = document.getElementById('myUserId');
                this.myUsername = document.getElementById('myUsername');
                this.userAvatar = document.getElementById('userAvatar');
                this.friendIdInput = document.getElementById('friendIdInput');
                this.groupNameInput = document.getElementById('groupNameInput');
                this.groupIdInput = document.getElementById('groupIdInput');
                this.chatTitle = document.getElementById('chatTitle');
                this.chatSubtitle = document.getElementById('chatSubtitle');
                this.messagesContainer = document.getElementById('messagesContainer');
                this.messageInput = document.getElementById('messageInput');
                this.sendBtn = document.getElementById('sendBtn');
                this.status = document.getElementById('status');
                this.privateChats = document.getElementById('privateChats');
                this.groupChats = document.getElementById('groupChats');
                
                // 服务器选择变化事件
                this.serverSelect.addEventListener('change', () => {
                    if (this.serverSelect.value === 'custom') {
                        this.customServerGroup.classList.remove('hidden');
                    } else {
                        this.customServerGroup.classList.add('hidden');
                    }
                });
                
                // 回车发送消息
                this.messageInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter' && !this.sendBtn.disabled) {
                        this.sendMessage();
                    }
                });
            }

            connect() {
                try {
                    const serverUrl = this.getSelectedServerUrl();
                    this.ws = new WebSocket(serverUrl);
                    
                    this.ws.onopen = () => {
                        this.isConnected = true;
                        this.updateStatus('已连接', 'connected');
                    };
                    
                    this.ws.onmessage = (event) => {
                        const message = JSON.parse(event.data);
                        this.handleMessage(message);
                    };
                    
                    this.ws.onclose = () => {
                        this.isConnected = false;
                        this.updateStatus('连接断开', 'disconnected');
                        setTimeout(() => this.connect(), 3000);
                    };
                    
                    this.ws.onerror = (error) => {
                        console.error('WebSocket错误:', error);
                        this.updateStatus('连接错误', 'disconnected');
                    };
                } catch (error) {
                    console.error('连接失败:', error);
                    this.updateStatus('连接失败', 'disconnected');
                }
            }

            getSelectedServerUrl() {
                const selectedValue = this.serverSelect.value;
                if (selectedValue === 'custom') {
                    const customUrl = this.customServerInput.value.trim();
                    return customUrl || 'ws://localhost:5000/ws'; // 默认值
                }
                return selectedValue;
            }

            register() {
                const username = this.usernameInput.value.trim();
                if (!username) {
                    alert('请输入用户名');
                    return;
                }

                if (!this.isConnected) {
                    alert('连接未建立，请稍后重试');
                    return;
                }

                const message = {
                    Type: 'register',
                    Username: username,
                    Content: '',
                    Timestamp: new Date().toISOString()
                };
                this.ws.send(JSON.stringify(message));
            }

            login() {
                const userId = this.userIdInput.value.trim();
                if (!userId) {
                    alert('请输入账号ID');
                    return;
                }

                if (!this.isConnected) {
                    alert('连接未建立，请稍后重试');
                    return;
                }

                const message = {
                    Type: 'login',
                    UserId: userId,
                    Content: '',
                    Timestamp: new Date().toISOString()
                };
                this.ws.send(JSON.stringify(message));
            }

            handleMessage(message) {
                switch (message.Type) {
                    case 'register':
                        if (message.Success) {
                            this.currentUser = message.Data;
                            this.showChatInterface();
                            this.addSystemMessage(`注册成功！您的账号ID是: ${this.currentUser.UserId}`);
                        } else {
                            alert('注册失败: ' + message.Message);
                        }
                        break;
                        
                    case 'login':
                        if (message.Success) {
                            this.currentUser = message.Data;
                            this.showChatInterface();
                            this.addSystemMessage(`登录成功！欢迎回来 ${this.currentUser.Username}`);
                            this.loadUserGroups();
                        } else {
                            alert('登录失败: ' + message.Message);
                        }
                        break;
                        
                    case 'private':
                        if (message.Success !== undefined) {
                            if (message.Success) {
                                // 显示自己发送的私聊消息
                                const sentMessage = message.Data;
                                sentMessage.Username = this.currentUser.Username;
                                sentMessage.UserId = this.currentUser.UserId;
                                this.addMessage(sentMessage, 'sent');
                            } else {
                                this.addErrorMessage(message.Message);
                            }
                        } else {
                            // 接收到的私聊消息（来自其他用户）
                            this.addMessage(message, 'received');
                            this.updatePrivateChatList(message.UserId, message.Username);
                        }
                        break;
                        
                    case 'group':
                        if (message.Success !== undefined) {
                            if (message.Success) {
                                // 显示自己发送的消息
                                const sentMessage = message.Data;
                                sentMessage.Username = this.currentUser.Username;
                                sentMessage.UserId = this.currentUser.UserId;
                                this.addMessage(sentMessage, 'sent');
                            } else {
                                this.addErrorMessage(message.Message);
                            }
                        } else {
                            // 接收到的群聊消息（来自其他用户）
                            this.addMessage(message, 'received');
                        }
                        break;
                        
                    case 'create_group':
                        if (message.Success) {
                            this.addSystemMessage(`群聊创建成功！群号: ${message.Data.GroupId}`);
                            this.updateGroupChatList(message.Data.GroupId, message.Data.GroupName);
                        } else {
                            alert('创建群聊失败: ' + message.Message);
                        }
                        break;
                        
                    case 'join_group':
                        if (message.Success) {
                            this.addSystemMessage(`成功加入群聊: ${message.Data.GroupName}`);
                            this.updateGroupChatList(message.Data.GroupId, message.Data.GroupName);
                        } else {
                            alert('加入群聊失败: ' + message.Message);
                        }
                        break;
                        
                    case 'get_groups':
                        if (message.Success) {
                            this.loadGroupChats(message.Data);
                        }
                        break;
                        
                    case 'system':
                        this.addSystemMessage(message.Content);
                        break;
                        
                    default:
                        console.log('未处理的消息类型:', message);
                        break;
                }
            }

            showChatInterface() {
                this.loginSection.classList.add('hidden');
                this.chatSection.classList.add('active');
                this.myUserId.textContent = this.currentUser.UserId;
                this.myUsername.textContent = this.currentUser.Username;
                this.userAvatar.textContent = this.currentUser.Username.charAt(0).toUpperCase();
            }

            loadUserGroups() {
                const message = {
                    Type: 'get_groups',
                    UserId: this.currentUser.UserId,
                    Content: '',
                    Timestamp: new Date().toISOString()
                };
                this.ws.send(JSON.stringify(message));
            }

            startPrivateChat() {
                const friendId = this.friendIdInput.value.trim();
                if (!friendId) {
                    alert('请输入好友账号ID');
                    return;
                }

                if (friendId === this.currentUser.UserId) {
                    alert('不能和自己聊天');
                    return;
                }

                this.updatePrivateChatList(friendId, `用户${friendId}`);
                this.switchToChat('private', friendId, `用户${friendId}`);
                this.friendIdInput.value = '';
            }

            createGroup() {
                const groupName = this.groupNameInput.value.trim();
                if (!groupName) {
                    alert('请输入群聊名称');
                    return;
                }

                const message = {
                    Type: 'create_group',
                    GroupName: groupName,
                    Content: '',
                    Timestamp: new Date().toISOString()
                };
                this.ws.send(JSON.stringify(message));
                this.groupNameInput.value = '';
            }

            joinGroup() {
                const groupId = this.groupIdInput.value.trim();
                if (!groupId) {
                    alert('请输入群聊ID');
                    return;
                }

                const message = {
                    Type: 'join_group',
                    GroupId: groupId,
                    Content: '',
                    Timestamp: new Date().toISOString()
                };
                this.ws.send(JSON.stringify(message));
                this.groupIdInput.value = '';
            }

            updatePrivateChatList(friendId, friendName) {
                if (!this.privateChatData.has(friendId)) {
                    this.privateChatData.set(friendId, { id: friendId, name: friendName });
                    this.renderPrivateChats();
                }
            }

            updateGroupChatList(groupId, groupName) {
                if (!this.groupChatData.has(groupId)) {
                    this.groupChatData.set(groupId, { id: groupId, name: groupName });
                    this.renderGroupChats();
                }
            }

            loadGroupChats(groups) {
                this.groupChatData.clear();
                groups.forEach(group => {
                    this.groupChatData.set(group.GroupId, {
                        id: group.GroupId,
                        name: group.GroupName,
                        memberCount: group.MemberCount
                    });
                });
                this.renderGroupChats();
            }

            renderPrivateChats() {
                this.privateChats.innerHTML = '';
                this.privateChatData.forEach(chat => {
                    const chatItem = document.createElement('div');
                    chatItem.className = 'chat-item';
                    chatItem.onclick = () => this.switchToChat('private', chat.id, chat.name);
                    
                    chatItem.innerHTML = `
                        <div class="chat-item-header">
                            <div class="chat-avatar">${chat.name.charAt(0).toUpperCase()}</div>
                            <div class="chat-info">
                                <h4>${chat.name}</h4>
                                <div class="chat-id">账号: ${chat.id}</div>
                            </div>
                        </div>
                    `;
                    
                    this.privateChats.appendChild(chatItem);
                });
            }

            renderGroupChats() {
                this.groupChats.innerHTML = '';
                this.groupChatData.forEach(group => {
                    const chatItem = document.createElement('div');
                    chatItem.className = 'chat-item';
                    chatItem.onclick = () => this.switchToChat('group', group.id, group.name);
                    
                    chatItem.innerHTML = `
                        <div class="chat-item-header">
                            <div class="chat-avatar">${group.name.charAt(0).toUpperCase()}</div>
                            <div class="chat-info">
                                <h4>${group.name}</h4>
                                <div class="chat-id">群号: ${group.id}${group.memberCount ? ` (${group.memberCount}人)` : ''}</div>
                            </div>
                        </div>
                    `;
                    
                    this.groupChats.appendChild(chatItem);
                });
            }

            switchToChat(type, id, name) {
                this.currentChat = { type, id, name };
                
                // 更新聊天标题
                this.chatTitle.textContent = name;
                this.chatSubtitle.textContent = type === 'private' ? `私聊 - 账号: ${id}` : `群聊 - 群号: ${id}`;
                
                // 清空消息区域
                this.messagesContainer.innerHTML = '';
                
                // 启用输入
                this.messageInput.disabled = false;
                this.sendBtn.disabled = false;
                this.messageInput.focus();
                
                // 高亮选中项
                document.querySelectorAll('.chat-item').forEach(item => item.classList.remove('active'));
                event.currentTarget.classList.add('active');
            }

            sendMessage() {
                const content = this.messageInput.value.trim();
                if (!content || !this.currentChat) return;

                const message = {
                    Content: content,
                    Timestamp: new Date().toISOString()
                };

                if (this.currentChat.type === 'private') {
                    message.Type = 'private';
                    message.TargetUserId = this.currentChat.id;
                } else {
                    message.Type = 'group';
                    message.GroupId = this.currentChat.id;
                }

                this.ws.send(JSON.stringify(message));
                this.messageInput.value = '';
            }

            addMessage(message, type) {
                if (!this.currentChat) return;
                
                // 检查消息是否属于当前聊天
                if (this.currentChat.type === 'private') {
                    // 私聊：只显示与当前聊天对象相关的消息（发送给对方或从对方接收）
                    if (type === 'sent') {
                        // 自己发送的消息，不需要过滤
                    } else if (message.UserId !== this.currentChat.id) {
                        // 接收的消息，必须来自当前聊天对象
                        return;
                    }
                } else if (this.currentChat.type === 'group') {
                    // 群聊：只显示当前群的消息
                    if (message.GroupId !== this.currentChat.id) return;
                }

                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${type}`;
                
                const time = new Date(message.Timestamp).toLocaleTimeString();
                const senderName = message.Username || message.UserId || '未知用户';
                
                let content = '';
                if (type === 'sent') {
                    content = `
                        <div class="message-header">我 ${time}</div>
                        <div class="message-content">${message.Content}</div>
                    `;
                } else {
                    content = `
                        <div class="message-header">${senderName} ${time}</div>
                        <div class="message-content">${message.Content}</div>
                    `;
                }
                
                messageDiv.innerHTML = content;
                this.messagesContainer.appendChild(messageDiv);
                this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
            }

            addSystemMessage(content) {
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message system';
                messageDiv.innerHTML = `<div class="message-content">${content}</div>`;
                this.messagesContainer.appendChild(messageDiv);
                this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
            }

            addErrorMessage(content) {
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message error';
                messageDiv.innerHTML = `<div class="message-content">❌ ${content}</div>`;
                this.messagesContainer.appendChild(messageDiv);
                this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
            }

            updateStatus(text, className) {
                this.status.textContent = text;
                this.status.className = `status ${className}`;
            }
        }

        // 全局函数
        function register() {
            app.register();
        }

        function login() {
            app.login();
        }

        function switchTab(tabName) {
            // 更新标签按钮
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            event.currentTarget.classList.add('active');
            
            // 切换标签内容
            document.getElementById('privateTab').classList.toggle('hidden', tabName !== 'private');
            document.getElementById('groupTab').classList.toggle('hidden', tabName !== 'group');
        }

        function startPrivateChat() {
            app.startPrivateChat();
        }

        function createGroup() {
            app.createGroup();
        }

        function joinGroup() {
            app.joinGroup();
        }

        function sendMessage() {
            app.sendMessage();
        }

        // 启动应用
        const app = new ChatApp();
    </script>
</body>
</html>